import jwt
from django.shortcuts import render, get_object_or_404
from patient.models import *
import json, random, string
from django.views import View
from django.http.response import HttpResponse, JsonResponse
import datetime
from hashlib import sha256
from decimal import Decimal
from datetime import datetime, timedelta, timezone
from patient.qiniu import qiuniuImg
from django.core.exceptions import ObjectDoesNotExist
from patient.qiniu import qiuniuImg



class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, Decimal):
            return float(o)
        return super().default(o)


class CustomJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d')
        elif isinstance(obj, Decimal):
            return float(obj)
        return super().default(obj)


class OrderCenter(View):
    def post(self, req):
        info = json.loads(req.body.decode('utf-8'))
        phone = info.get('phone')
        name = HospitalEscort.objects.filter(e_phone=phone).first()
        msg = Orders.objects.filter(escort=name)
        try:
            return HttpResponse(json.dumps(list(msg.values()), ensure_ascii=False, cls=CustomJSONEncoder))
        except Exception as e:
            return JsonResponse({'message': '错误%s'%e})


def order_status(req):
    msg = json.loads(req.body.decode('utf-8'))
    phone = msg.get('phone')
    name = HospitalEscort.objects.filter(e_phone=phone).first()
    status = msg.get('type')
    info = Orders.objects.filter(status=status, escort=name).all()
    return HttpResponse(json.dumps(list(info.values()), ensure_ascii=False, cls=CustomJSONEncoder))


def get_escort(req):
    msg = json.loads(req.body.decode('utf-8'))
    phone = msg.get('phone')
    info = HospitalEscort.objects.filter(e_phone=phone)
    return HttpResponse(json.dumps(list(info.values()), ensure_ascii=False, cls=CustomJSONEncoder))



class AcceptOrdersView(View):
    """获取所有的订单信息"""
    def get(self, request):
        queryset = Orders.objects.filter(status='待服务')
        hospitals = Hospital.objects.all()
        order_info = [i.tojson() for i in queryset]
        hospital_names = sorted([hospital.h_name for hospital in hospitals])
        return JsonResponse({'order_info': order_info, 'hospital_names': hospital_names}, status=200)


class QueryOrdersView(View):
    """通过时间和医院查询订单信息"""
    def get(self, request):
        queryset = Orders.objects.all()
        data_order_time = request.GET.get('order_time', None)
        data_order_hospital = request.GET.get('order_hospital', None)
        if data_order_time == '1日内':
            now_time = datetime.now().date()
            queryset = queryset.filter(expect_time__date=now_time, status='待服务')
        elif data_order_time == '3日内':
            today_end = datetime.now().date() - timedelta(days=3)
            queryset = queryset.filter(expect_time__gte=today_end, status='待服务')
        elif data_order_time == '7日内':
            today_end = datetime.now().date() - timedelta(days=7)
            queryset = queryset.filter(expect_time__gte=today_end, status='待服务')
        if data_order_hospital:
            queryset = queryset.filter(hospital=data_order_hospital, status='待服务')

        order_info = [i.tojson() for i in queryset]
        return JsonResponse({'order_info': order_info}, status=200)

class EscortLogin(View):
    """陪诊师登录注册"""
    def post(self, request):
        try:
            data = json.loads(request.body.decode('utf-8'))
            phone = data.get('phone')
            password = data.get('password')
            hash_pwd = sha256(password.encode('utf-8')).hexdigest()
            data = HospitalEscort.objects.filter(e_phone=phone).first()
            if data:
                if data.e_password == hash_pwd:
                    return JsonResponse({'code': 200, 'msg': '登录成功'}, status=200, safe=False)
                else:
                    return JsonResponse({'code': 400, 'msg': '密码错误'})
            else:
                HospitalEscort.objects.create(e_phone=phone, e_password=hash_pwd, e_name='用户', favorable_rate=0, order_count=0, img='https://pic4.zhimg.com/v2-89645d664e2b048afd8060c7ed8cc5e3_r.jpg')
                return JsonResponse({'code': 200, 'msg': '注册登录成功'}, status=200, safe=False)
        except Exception as e:
            return JsonResponse(str(e), status=400, safe=False)


class SearchEscortView(View):
    """查询陪诊师"""
    def get(self, request):
        phone_a = request.GET.get('phone')
        try:
            name = HospitalEscort.objects.filter(e_phone=phone_a)
            escorts_lst = []
            for escort in name:
                escort_info = {
                    'e_name': escort.e_name,
                    'e_phone': escort.e_phone,
                    'e_age': escort.e_age,
                    'e_sex': escort.e_sex,
                    'address': escort.address,
                    'favorable_rate': escort.favorable_rate,
                    'order_count': escort.order_count,
                    'status': escort.status,
                    'img': escort.img,
                    'e_card': escort.e_card,
                    'occupancy': escort.occupancy
                }
                escorts_lst.append(escort_info)
            return JsonResponse({'escorts': escorts_lst})
        except Exception as e:
            return JsonResponse({'error': '查询错误'})

    def post(self, request):
        try:
            import json
            data = json.loads(request.body)
            phone = data.get('params').get('phone')
            checked = data.get('params').get('checked')
            checked = checked.lower() == 'true'
            escort = HospitalEscort.objects.get(e_phone=phone)
            if checked:
                escort.status = '空闲'
            else:
                escort.status = '工作'
            escort.save()
            return JsonResponse({'message': '更新成功'})
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)

    def put(self, request, userphone):
        """通过用户手机号更新用户信息"""
        try:
            data = json.loads(request.body)
            new_avatar = data.get('avatar')
            if new_avatar:
                HospitalEscort.objects.filter(e_phone=userphone).update(img=new_avatar)
                return JsonResponse({'message': '修改头像成功'}, status=200)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)


class EscortCertificationView(View):
    """提交陪诊师信息"""
    def post(self, request):
        data = json.loads(request.body)
        phone = data.get('e_phone')
        escort = HospitalEscort.objects.filter(e_phone=phone)
        if escort:
            checked = data.get('checked', [])
            del data['checked']
            update_info = HospitalEscort.objects.filter(e_phone=phone).update(**data)
            if update_info == 0:
                return JsonResponse({'error': '更新陪诊师信息失败'}, status=500, safe=False)
            services = [EscortServiceItem.objects.get(id=i) for i in checked]
            escort = HospitalEscort.objects.filter(e_phone=phone).first()
            escort.service_items.add(*services)
            escort.occupancy = '已入驻'
            escort.save()
            return JsonResponse('提交陪诊师实名认证成功', status=200, safe=False)
        else:
            return JsonResponse({'error': '未找到对应手机号的陪诊师记录'}, status=404, safe=False)

class QiniuTokenView(View):
    """七牛token"""
    def get(self, request):
        Qiniu = qiuniuImg()
        token = Qiniu.get_token()
        if token is None:
            return JsonResponse({'error': '获取token失败，token为None'}, status=400)
        return JsonResponse({'token': token}, status=200)


class QiniuDownloadView(View):
    """七牛图片下载"""
    def post(self, request):
        data = json.loads(request.body)
        key = data['key']
        Qiniu = qiuniuImg()
        download_url = Qiniu.download_file(key=key)
        if download_url is None:
            return JsonResponse({'error': '获取下载网址失败'}, status=400)
        return JsonResponse({'download_url': download_url}, status=200)


class ChangePwdView(View):
    """修改密码"""
    def post(self, request):
        try:
            data = json.loads(request.body)
            original_phone = data.get('phone')
            new_pwd = data.get('new_pwd')
            if not original_phone or not new_pwd:
                return JsonResponse({'code': 400, 'message': '手机号和新密码不能为空'}, status=400)
            new_hashed_pwd = sha256(new_pwd.encode('utf-8')).hexdigest()
            try:
                user = HospitalEscort.objects.filter(e_phone=original_phone)
                if user:
                    user.update(e_password=new_hashed_pwd)
                    return JsonResponse({'code': 200, 'message': '密码更改成功'})
            except ObjectDoesNotExist:
                return JsonResponse({'code': 404, 'message': '用户不存在'}, status=404)
        except json.JSONDecodeError:
            return JsonResponse({'code': 400, 'message': '请求数据格式错误'}, status=400)
        except Exception as e:
            return JsonResponse({'code': 500, 'error': str(e)}, status=500)


class OrderView(View):
    """通过手机号查询订单"""
    def get(self, request):
        name_a = request.GET.get('e_name')
        total_income = 0.0
        completed_order_count = 0
        try:
            user = Orders.objects.filter(escort=name_a)
            for order in user:
                if order.expect_time.date() == datetime.now().date() and order.status == '已完成':
                    total_income += int(order.price)  # 将 order.price 转换为浮点数进行相加
                    completed_order_count += 1
            order_data = {
                'total_income': total_income,
                'completed_order_count': completed_order_count
            }
            return JsonResponse({'orders': order_data, 'code': 200}, status=200, safe=False)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)


class AllOrders(View):
    """通过手机号查询用户信息"""
    def get(self, request):
        user_name = request.GET.get('name')
        try:
            users = Orders.objects.filter(escort=user_name)
            # 三个月份时间
            now_year = datetime.now().strftime('%Y')
            now_mouth = datetime.now().strftime('%m')
            now_year_mouth = now_year + '-' + now_mouth
            now_mouth = int(now_mouth)
            now_year = int(now_year)
            previous_first_year_mouth = ''
            previous_second_year_mouth = ''
            # 当现在的月份是1月
            if now_mouth == 1:
                # 上一个月份
                # 上个月的年份要-1 上个月的年份
                previous_first_year = now_year - 1
                # 上个月的月份为12 上个月的月份
                previous_first_mouth = 12
                # 上个月的年月 转为字符串
                previous_first_year_mouth = str(previous_first_year) + '-' + str(previous_first_mouth)
                # 上上个月的年份要-1 上上个月的年份
                previous_second_year = now_year - 1
                # 上上个月的月份为上个月-1 上上个月的月份
                previous_second_mouth = previous_first_mouth - 1
                # 上上个月的年月 转为字符串
                previous_second_year_mouth = str(previous_second_year) + '-' + str(previous_second_mouth)
            elif now_mouth == 2:
                # 上个月的日期
                # 上个月的年份
                previous_first_year = now_year
                # 上个月的月份
                previous_first_mouth = now_mouth - 1
                # 上个月的年月
                previous_first_year_mouth = str(previous_first_year) + '-' + str(previous_first_mouth)
                # 上上个月的日期
                # 上上个月的年份
                previous_second_year = now_year - 1
                # 上上个月的月份
                previous_second_mouth = 12
                # 上上个月的年月
                previous_second_year_mouth = str(previous_second_year) + '-' + str(previous_second_mouth)
            else:
                previous_first_mouth = now_mouth - 1
                previous_second_mouth = previous_first_mouth - 1

            # 首页订单数据
            prices = 0
            all_prices = 0
            user_info = []
            nums = 0
            all_nums = 0

            # 上个月的已完成订单数
            previous_first_mouth_nums = 0
            # 上个月已完成的订单总收益
            previous_first_mouth_earnings = 0
            # 上上个月已经完成的订单数
            previous_second_mouth_nums = 0
            # 上上个月已经完成的订单总收益
            previous_second_mouth_earnings = 0

            refund_amount = 0
            await_complete = 0
            already_complete = 0
            already_evaluate = 0
            for user in users:
                all_prices += user.price
                all_nums += 1
                # 上个月的订单量和订单收益
                if previous_first_year_mouth == user.expect_time.strftime('%Y-%m'):
                    if user.status == '已完成':
                        previous_first_mouth_nums += 1
                        previous_first_mouth_earnings += user.price
                # 上上个月的订单数和订单收益
                if previous_second_year_mouth == user.expect_time.strftime('%Y-%m'):
                    if user.status == '已完成':
                        previous_second_mouth_nums += 1
                        previous_second_mouth_earnings += user.price

                # 首页总收益，总销量，订单收入，总订单数，订单状态
                if user.status != '已取消':
                    prices += user.price
                    nums += 1
                else:
                    refund_amount = user.price
                    continue
                if user.status == '待完成':
                    await_complete += 1
                if user.status == '已完成':
                    already_complete += 1
                if user.status == '已评价':
                    already_evaluate += 1
            user_ls = {
                'prices': prices,
                'all_prices': all_prices,
                'nums': nums,
                'all_nums': all_nums,
                'refund_amount': refund_amount,
                'await_complete': await_complete,
                'already_complete': already_complete,
                'already_evaluate': already_evaluate,
                'now_year_mouth': now_year_mouth,
                'previous_first_year_mouth': previous_first_year_mouth,
                'previous_second_year_mouth': previous_second_year_mouth,
                'previous_first_mouth_nums': previous_first_mouth_nums,
                'previous_first_mouth_earnings': previous_first_mouth_earnings,
                'previous_second_mouth_nums': previous_second_mouth_nums,
                'previous_second_mouth_earnings': previous_second_mouth_earnings,
            }
            user_info.append(user_ls)
            return JsonResponse(user_info, status=200, safe=False)
        except User.DoesNotExist:
            return JsonResponse({'error': '用户不存在'}, status=404)
        except Exception as e:
            return JsonResponse({'error': f'查询用户信息出错: {str(e)}'}, status=500)


class WeekendOrders(View):
    """通过手机号查询用户信息"""
    def get(self, request):
        user_name = request.GET.get('user_name')
        now_week_mon = request.GET.get('now_week_mon')
        now_week_sun = request.GET.get('now_week_sun')
        up_first_week_mon = request.GET.get('up_first_week_mon')
        up_first_week_sun = request.GET.get('up_first_week_sun')
        up_second_week_mon = request.GET.get('up_second_week_mon')
        up_second_week_sun = request.GET.get('up_second_week_sun')
        # 本周的日期
        data_now_week = []
        current_date = datetime.strptime(now_week_mon, '%Y-%m-%d')
        now_week_sun = datetime.strptime(now_week_sun, '%Y-%m-%d')
        while current_date <= now_week_sun:
            data_now_week.append(current_date.strftime('%Y-%m-%d'))
            current_date += timedelta(days=1)
        # 上周的日期
        up_first_week = []
        current_date = datetime.strptime(up_first_week_mon, '%Y-%m-%d')
        up_first_week_sun = datetime.strptime(up_first_week_sun, '%Y-%m-%d')
        while current_date <= up_first_week_sun:
            up_first_week.append(current_date.strftime('%Y-%m-%d'))
            current_date += timedelta(days=1)
        # 上上周的日期
        up_second_week = []
        current_date = datetime.strptime(up_second_week_mon, '%Y-%m-%d')
        up_second_week_sun = datetime.strptime(up_second_week_sun, '%Y-%m-%d')
        while current_date <= up_second_week_sun:
            up_second_week.append(current_date.strftime('%Y-%m-%d'))
            current_date += timedelta(days=1)
        try:
            users = Orders.objects.filter(escort=user_name)
            # 本周的列表
            now_week_price = 0
            now_week_nums = 0
            now_week_ls = []
            # 上周的列表
            up_first_week_price = 0
            up_first_week_nums = 0
            up_first_week_ls = []
            # 上上周的列表
            up_second_week_price = 0
            up_second_week_nums = 0
            up_second_week_ls = []
            for user in users:
                # 本周订单总价格和订单量
                for date in data_now_week:
                    if user.expect_time.strftime('%Y-%m-%d') == date:
                        now_week_price += user.price
                        now_week_nums += 1
                        now_week_info = {
                            'now_week_price': now_week_price,
                            'now_week_nums': now_week_nums,
                        }
                        now_week_ls.append(now_week_info)
                # 上周的订单总价格和订单量
                for date in up_first_week:
                    if user.expect_time.strftime('%Y-%m-%d') == date:
                        up_first_week_price += user.price
                        up_first_week_nums += 1
                        up_first_week_info = {
                            'up_first_week_price': up_first_week_price,
                            'up_first_week_nums': up_first_week_nums,
                        }
                        up_first_week_ls.append(up_first_week_info)
                # 上上周的订单总价格和订单量
                for date in up_second_week:
                    if user.expect_time.strftime('%Y-%m-%d') == date:
                        up_second_week_price += user.price
                        up_second_week_nums += 1
                        up_second_week_info = {
                            'up_second_week_price': up_second_week_price,
                            'up_second_week_nums': up_second_week_nums,
                        }
                        up_second_week_ls.append(up_second_week_info)
            return JsonResponse({'now_week_ls': now_week_ls, 'up_first_week_ls': up_first_week_ls, 'up_second_week_ls': up_second_week_ls}, safe=False)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=400)


class ScoreView(View):
    """查询陪诊师评分"""
    def post(self, request):
        data = json.loads(request.body)
        phone = data.get('phone')
        escort = HospitalEscort.objects.filter(e_phone=phone).first()
        try:
            user_orders = Orders.objects.filter(escort=escort)
            total_score = sum(order.score for order in user_orders)
            average_score = total_score / len(user_orders) if user_orders else 0
            rounded_average_score = round(average_score, 1)
            return JsonResponse({'average_score': rounded_average_score}, status=200, safe=False)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=400)


